package com.xidian.zhiancloud.service.dangerWorkTicket;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.*;
import com.xidian.zhiancloud.dao.syset.SysPositionMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dao.workTicket.WorkTicketMapper;
import com.xidian.zhiancloud.dao.workTicket.WorkTicketTemplateMapper;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.DelayApplicationApprove;
import com.xidian.zhiancloud.model.UnsafeWorkApprove;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysPosition;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.model.workSupervise.ReviewWorkBefore;
import com.xidian.zhiancloud.model.workSupervise.SuperviseWork;
import com.xidian.zhiancloud.model.workSupervise.SuspendWork;
import com.xidian.zhiancloud.model.dangerWorkTicket.WorkTicket;
import com.xidian.zhiancloud.model.dangerWorkTicket.WorkTicketTemplate;
import com.xidian.zhiancloud.qo.dangerWorkTicket.WorkTicketQO;
import com.xidian.zhiancloud.service.dangerWorkTicket.WorkTicket.WorkTicketTemplateService;
import com.xidian.zhiancloud.vo.dangerWorkTicket.DelayApplicationApproveVO;
import com.xidian.zhiancloud.vo.dangerWorkTicket.UnsafeWorkApproveVO;
import com.xidian.zhiancloud.vo.dangerWorkTicket.WorkTicketVO;
import com.xidian.zhiancloud.vo.dangerWorkTicket.workSupervise.ReviewWorkBeforeVO;
import com.xidian.zhiancloud.vo.dangerWorkTicket.workSupervise.SuspendWorkVO;
import com.xidian.zhiancloud.vo.dangerWorkTicket.workSupervise.WorkSuperviseDTOVO;
import com.xidian.zhiancloud.vo.dangerWorkTicket.workSupervise.WorkSuperviseVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WorkSuperviseService extends ServiceImpl<WorkTicketMapper, WorkTicket> implements IService<WorkTicket> {

    @Autowired
    private WorkSuperviseMapper workSuperviseMapper;

    @Autowired
    private WorkTicketMapper workTicketMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPositionMapper sysPositionMapper;

    @Autowired
    private UnsafeWorkApproveMapper unsafeWorkApproveMapper;

    @Autowired
    private DelayApplicationApproveMapper delayApplicationApproveMapper;

    @Autowired
    private ReviewWorkBeforeMapper reviewWorkBeforeMapper;

    @Autowired
    private SuspendWorkMapper suspendWorkMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private WorkTicketTemplateMapper workTicketTemplateMapper;

    @Autowired
    private SuperviseWorkMapper superviseWorkMapper;

    @Autowired
    private WorkTicketTemplateService workTicketTemplateService;

    /**
     * 查看作业票需要提供作业票id，即其他几张效标的relateWorkId
     *
     * @param id
     * @return
     */
    public WorkSuperviseDTOVO getVOById(Long id) {
        // 作业基本信息
        WorkTicket workTicket = workTicketMapper.selectById(id);
        if (workTicket == null) {
            throw new CustomizeException(GeneralResponseEnums.GET_FAILED);
        }

        // 与作业票id相关的几个记录
        // 审批记录
        LambdaQueryWrapper<UnsafeWorkApprove> query = Wrappers.<UnsafeWorkApprove>lambdaQuery();
        query.eq(UnsafeWorkApprove::getRelateWorkId, id);
        List<UnsafeWorkApprove> unsafeWorkApproveS = unsafeWorkApproveMapper.selectList(query);

        // 延期申请审批记录
        LambdaQueryWrapper<DelayApplicationApprove> query1 = Wrappers.<DelayApplicationApprove>lambdaQuery();
        query1.eq(DelayApplicationApprove::getRelateWorkId, id);
        List<DelayApplicationApprove> delayApplicationApproveS = delayApplicationApproveMapper.selectList(query1);

        // 作业前检查记录
        LambdaQueryWrapper<ReviewWorkBefore> query2 = Wrappers.<ReviewWorkBefore>lambdaQuery();
        query2.eq(ReviewWorkBefore::getRelateWorkId, id);
        List<ReviewWorkBefore> reviewWorkBeforeS = reviewWorkBeforeMapper.selectList(query2);

        // 作业监督记录
        LambdaQueryWrapper<SuperviseWork> query3 = Wrappers.<SuperviseWork>lambdaQuery();
        query3.eq(SuperviseWork::getRelateWorkId, id);
        List<SuperviseWork> workSuperviseS = superviseWorkMapper.selectList(query3);

        // 作业中止记录
        LambdaQueryWrapper<SuspendWork> query4 = Wrappers.<SuspendWork>lambdaQuery();
        query4.eq(SuspendWork::getRelateWorkId, id);
        List<SuspendWork> suspendWorkS = suspendWorkMapper.selectList(query4);

        // 新建工作监督类
        WorkSuperviseDTOVO res = new WorkSuperviseDTOVO();

        // 返回作业基本信息
        WorkTicketVO vo = new WorkTicketVO();
        BeanUtils.copyProperties(workTicket, vo);

        SysUser creator = sysUserMapper.selectById(vo.getCreatorId());                      // 作业创建人
        vo.setCreatorName(creator == null ? "该用户不存在" : creator.getName());
        SysPosition position = sysPositionMapper.selectById(vo.getPositionId());            // 作业位置/区域
        vo.setLocationName(position == null ? "该位置不存在" : position.getName());
        SysUser guardian = sysUserMapper.selectById(vo.getGuardianId());
        vo.setGuardianName(guardian == null ? "该用户不存在" : guardian.getName());          // 作业监督人
        SysUser principal = sysUserMapper.selectById(vo.getPrincipalId());
        vo.setPrincipalName(principal == null ? "该用户不存在" : principal.getName());       // 作业负责人
        String template = workTicketTemplateMapper.selectById(vo.getTicketType()).getName();
        vo.setWorkTemplateName(template == null ? "该作业票不存在" : template);

        String ids_s = vo.getWorkerIds();                                                   // 现场作业人员
        long[] ids_l = Arrays.stream(ids_s.split(",")).mapToLong(Long::parseLong).toArray();
        List<String> names = Arrays.stream(ids_l).mapToObj(tmp_id -> {
            SysUser workers = sysUserMapper.selectById(tmp_id);
            return workers == null ? "该用户已被删除" : workers.getName();
        }).collect(Collectors.toList());
        vo.setWorkerNames(names);

        // 返回审批记录 unsafeWorkApproveS
        List<UnsafeWorkApproveVO> voList = new LinkedList<>();
        for (int i = 0; i < unsafeWorkApproveS.size(); i++) {
            UnsafeWorkApproveVO unsafeWorkApproveVO = new UnsafeWorkApproveVO();
            BeanUtils.copyProperties(unsafeWorkApproveS.get(i), unsafeWorkApproveVO);
            // 审批人姓名
            SysUser approver = sysUserMapper.selectById(unsafeWorkApproveVO.getApproverId());
            unsafeWorkApproveVO.setApproverName(approver == null ? "该用户不存在" : approver.getName());
            // 获取审批人所在部门
            Organization organization = organizationMapper.selectById(unsafeWorkApproveVO.getApproveOrganizationId());
            unsafeWorkApproveVO.setApproveOrganizationName(organization == null ? "该部门已被删除" : organization.getName());

            voList.add(unsafeWorkApproveVO);
        }

        // 审批记录详情

        // 返回延期申请审批记录 delayApplicationApproveS
        List<DelayApplicationApproveVO> voList1 = new LinkedList<>();
        for (int i = 0; i < delayApplicationApproveS.size(); i++) {
            DelayApplicationApproveVO delayApplicationApproveVO = new DelayApplicationApproveVO();
            BeanUtils.copyProperties(delayApplicationApproveS.get(i), delayApplicationApproveVO);
            // 审批人姓名
            SysUser approver = sysUserMapper.selectById(delayApplicationApproveVO.getApproverId());
            delayApplicationApproveVO.setApproverName(approver == null ? "该用户不存在" : approver.getName());
            // 获取审批人所在部门
            Organization organization = organizationMapper.selectById(delayApplicationApproveVO.getApproveOrganizationId());
            delayApplicationApproveVO.setApproveOrganizationName(organization == null ? "该部门已被删除" : organization.getName());

            voList1.add(delayApplicationApproveVO);
        }

        // 返回作业前检查记录 reviewWorkBeforeS
        // 作业前检查记录返回Map<String, int>，即Map<风险点, 是否通过>
        List<ReviewWorkBeforeVO> voList2 = new LinkedList<>();
        for (int i = 0; i < reviewWorkBeforeS.size(); i++) {
            ReviewWorkBeforeVO reviewWorkBeforeVO = new ReviewWorkBeforeVO();
            BeanUtils.copyProperties(reviewWorkBeforeS.get(i), reviewWorkBeforeVO);
            // 检查人姓名
            SysUser approver = sysUserMapper.selectById(reviewWorkBeforeVO.getCheckerId());
            reviewWorkBeforeVO.setCheckerName(approver == null ? "该用户不存在" : approver.getName());
            voList2.add(reviewWorkBeforeVO);
        }

        // 返回监督监护记录 workSuperviseS
        List<WorkSuperviseVO> voList3 = new LinkedList<>();
        for (int i = 0; i < workSuperviseS.size(); i++) {
            WorkSuperviseVO workSuperviseVO = new WorkSuperviseVO();
            BeanUtils.copyProperties(workSuperviseS.get(i), workSuperviseVO);

            String ids_ss = workSuperviseVO.getWorkerIds();                                                   // 现场作业人员
            long[] ids_ll = Arrays.stream(ids_ss.split(",")).mapToLong(Long::parseLong).toArray();
            List<String> namess = Arrays.stream(ids_ll).mapToObj(tmp_id -> {
                SysUser workers = sysUserMapper.selectById(tmp_id);
                return workers == null ? "该用户已被删除" : workers.getName();
            }).collect(Collectors.toList());
            workSuperviseVO.setWorkerNames(namess);

            SysUser guardian1 = sysUserMapper.selectById(workSuperviseVO.getSupervisorId());
            workSuperviseVO.setGuardianName(guardian1 == null ? "该用户不存在" : guardian1.getName());

            voList3.add(workSuperviseVO);
        }

        // 返回作业中止记录 suspendWorkS
        List<SuspendWorkVO> voList4 = new LinkedList<>();
        for (int i = 0; i < suspendWorkS.size(); i++) {
            SuspendWorkVO suspendWorkVO = new SuspendWorkVO();
            BeanUtils.copyProperties(suspendWorkS.get(i), suspendWorkVO);

            SysUser suspender = sysUserMapper.selectById(suspendWorkVO.getSuspenderId());
            suspendWorkVO.setSuspenderName(suspender == null ? "该用户不存在" : suspender.getName());

            SysUser recover = sysUserMapper.selectById(suspendWorkVO.getRecoverId());
            suspendWorkVO.setRecoverName(recover == null ? "该用户不存在" : recover.getName());

            voList4.add(suspendWorkVO);
        }

        // 返回riskList
        res.setRiskList(workTicketTemplateService.riskList(vo.getContent()));

        res.setWorkTicketVO(vo);
        res.setUnsafeWorkApproveVOList(voList);
        res.setDelayApplicationApproveVOList(voList1);
        res.setReviewWorkBeforeVOList(voList2);
        res.setWorkSuperviseVOList(voList3);
        res.setSuspendWorkVOList(voList4);

        return res;
    }

    public IPage<WorkTicketVO> getListByQO(WorkTicketQO workTicketQO) {
        Page<WorkTicketVO> page = new Page<>(workTicketQO.getCurrent(), workTicketQO.getSize());
        OrderItem orderItem = new OrderItem();
        // 排序
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);
        IPage<WorkTicketVO> res = workTicketMapper.getListByQO(page, workTicketQO);
        // 联表查询
        res.getRecords().forEach(
                vo -> {
                    Long ticketType = vo.getTicketType();
                    WorkTicketTemplate template = workTicketTemplateMapper.selectById(ticketType);
                    vo.setWorkTemplateName(
                            template == null ? "作业票类型已删除" : template.getName()
                    );
                }
        );
        return res;
    }




}
